
/**
 * H5 addUnionId
 * @returns {*}
 */
export function addUnionId () {
  // return uni.flux.http.post('/external/miniProgramAuthorize/v1/addUnionId', {
  //   code: uni.flux.store.state.wxCode,
  //   appId: uni.flux.store.state.appId,
  //   readerType: 2
  // })
}

// 用户相关api
/**
 * 1. 用户已经过授权电话号码
 * 2. 直接获取token
 * 3. 再去登录
 * @returns {Promise<void>}
 */
export function getTokenInfo () {
  return uni.flux.$api.user.authorize().then(async () => {
    await uni.flux.$api.user.getReaderInfo()
  }).finally(() => {
    uni.flux.isLogined()
  })
}

// weixin token
export async function authorize () {
  console.log('authorize test')
  if (uni.flux.store.state.env.isWeixin) {
    const loginCode = await uni.login()
    uni.flux.store.commit('setMiniProgramLoginCode', loginCode[1].code)
    return uni.flux.http.post('/external/miniProgramAuthorize/v1/authorize', {
      code: loginCode[1].code,
      appId: uni.flux.config.appId
    }).then((data) => {
      uni.flux.store.commit('setToken', data.token)
      return uni.flux.resolve()
    }).catch(error => {
      console.error('【获取token失败】', error)
      return uni.flux.reject()
    })
  }
}

/**
 * 根据token获取用户信息
 * @returns {*}
 */
export function getReaderInfo () {
  return uni.flux.http.get('/external/reader/v1/getReaderInfo').then(userInfo => {
    if (userInfo) {
      uni.flux.store.commit('setUserInfo', userInfo)
    }
    // #ifdef MP-WEIXIN
    // 暂停使用 位置授权 2021/07/08
    // uni.flux.$api.location.checkLocation()
    // #endif
    return uni.flux.resolve()
  }).catch(error => {
    return uni.flux.reject('获取用户信息失败：', error)
  }).finally(() => {
    uni.flux.isLogined()
  })
}

/**
 * 检测session是否过期
 * @param {Function} callback
 * { isExpired: false, errMsg: 'session_key 未过期，并且在本生命周期一直有效' }
 * { isExpired: true, errMsg: 'session_key 已经失效，需要重新执行登录流程' }
 */

export function checkSession () {
  return new Promise((resolve, reject) => {
    uni.checkSession({
      success: (res) => {
        console.log(res)
        resolve(true)
      },
      fail: async (res) => {
        console.log(res)
        reject(new Error(false))
      }
    })
  })
}

/**
 * 微信授权手机授权获取手机号码
 * @param e
 * @returns {Promise<unknown>}
 */
export async function getPhoneNumber (event) {
  return checkSession().then((res) => {
    console.log(res, 'session_key 未过期')
    return authPhone(event, true)
  }).catch(() => {
    console.log(res, 'session_key 已过期')
    return authPhone(event, false)
  })
}

export async function getMiniProgramLoginCode () {
  const loginCode = await uni.login()
  uni.flux.store.commit('setMiniProgramLoginCode', loginCode[1].code)
}

export async function authPhone (event, expires) {
  // checkSession 过期重新获取code
  if (!expires || !uni.flux.store.state.miniProgramLoginCode) {
    await getMiniProgramLoginCode()
  }
  return uni.flux.http.post('/external/miniProgramAuthorize/v1/authPhone', {
    code: uni.flux.store.state.miniProgramLoginCode,
    appId: uni.flux.config.appId,
    encryptedData: event.detail.encryptedData,
    iv: event.detail.iv
  }).then((data) => {
    if (data) {
      // console.log('重新【token 获取成功】：', data)
      uni.flux.store.commit('setToken', data)
    }
    return uni.flux.$api.user.getReaderInfo()
  }).catch(error => {
    // console.error('重新【token 获取失败】：', error)
    // 解密失败重新获取code
    getMiniProgramLoginCode()
    return uni.flux.reject(error)
  })
}

/**
 * localhost
 * H5 token
 * @returns {Promise<*>}
 */
export function loginByPhone () {
  return uni.flux.http.get('/external/code/v1/devH5Login', {
    code: '0618Yi100aNPFL1xWn200F214L18Yi1V',
    phone: uni.getStorageSync('testMyPhone') || uni.flux.utils.getQuery('phone')
  }).then(res => {
    console.log('localhost', res.token)
    if (res.token) {
      uni.flux.store.commit('setToken', res.token)
    }
    if (res.reader) {
      uni.flux.store.commit('setUserInfo', res.reader || {})
    }
    return uni.flux.isLogined()
  }).catch(error => {
    console.error('【获取token失败】', error)
    return uni.flux.isLogined()
  })
}

export function h5Authorize (type) {
  const myCode = uni.flux.store.state.wxCode || uni.getStorageSync('wxCode') || ''
  const manageTest = uni.flux.utils.getQuery('manageTest') || 0
  /**
   * 接口3个状态时会自动重定向，所以这里不需重复
   * 603 token过期
   * 600 帐号在其他设备登录
   * 602 用户未登录
   */
  if (type !== 600) {
    if (!myCode && !uni.flux.store.state.env.isDev && uni.flux.store.state.env.isH5 && manageTest === 0) {
      return uni.flux.$api.user.forWard(1)
    }
  }

  return uni.flux.http.post('/external/miniProgramAuthorize/v1/h5Authorize', {
    appId: uni.flux.store.state.appId,
    code: myCode,
    readerType: 2
  }).then(res => {
    if (res.token) {
      uni.flux.store.commit('setToken', res.token)
      uni.flux.$api.user.getReaderInfo()
    }
    uni.flux.isLogined()
    return uni.flux.resolve()
  }).catch(error => {
    uni.flux.isLogined()
    return uni.flux.reject(new Error(error))
  })
}

export function h5Authorize2 (type) {
  const myCode = uni.flux.store.state.wxCode || uni.getStorageSync('wxCode') || ''
  const manageTest = uni.flux.utils.getQuery('manageTest') || 0
  /**
   * 接口3个状态时会自动重定向，所以这里不需重复
   * 603 token过期
   * 600 帐号在其他设备登录
   * 602 用户未登录
   */
  if (type !== 600) {
    if (!myCode && !uni.flux.store.state.env.isDev && uni.flux.store.state.env.isH5 && manageTest === 0) {
      return uni.flux.$api.user.forWard(1)
    }
  }
  return uni.flux.http.post('/external/miniProgramAuthorize/v1/h5Authorize', {
    appId: uni.flux.store.state.appId,
    code: myCode,
    readerType: 2
  }).then(res => {
    if (res.token) {
      uni.flux.store.commit('setToken', res.token)
    }
    uni.flux.isLogined()
    return uni.flux.resolve()
  }).catch(error => {
    uni.flux.isLogined()
    return uni.flux.reject(new Error(error))
  })
}

export function testCheckCode () {
  return uni.flux.http.get('/external/code/v1/test/checkCode').then(userInfo => {
    // console.log('【获取用户信息】：', userInfo)
    if (userInfo) {
      uni.flux.store.commit('setUserInfo', userInfo)
    }
    return uni.flux.resolve()
  }).catch(error => {
    return uni.flux.reject('获取用户信息失败：', error)
  })
}

export function getShareParamByOfficialId () {
  return uni.flux.http.get('/external/miniProgram/v1/getShareParamByOfficialId', {
    url: encodeURIComponent(location.href.split('#')[0])
  }).then(res => {
    if (res) {
      jWeixin.config({
        debug: false,
        appId: 'wx6223f311b532c11d',
        timestamp: res.timestamp,
        nonceStr: res.nonceStr,
        signature: res.signature,
        openTagList: ['wx-open-launch-weapp'],
        jsApiList: [
          'checkJsApi',
          'onMenuShareAppMessage',
          'onMenuShareWechat',
          'onMenuShareTimeline',
          'shareAppMessage',
          'shareWechatMessage',
          'closeWindow',
          'scanQRCode'
        ]
      })

      jWeixin.error(function (err) {
        uni.flux.store.commit('setWxSdkReady', false)
        uni.flux.track.ShowWxSdkConfig()
        console.error('error：', err)
      })

      jWeixin.ready(function (res) {
        console.info('wx', res)
      })
    }
  })
}
/**
 * 退出登录
 * @return
 */
export function readerLoginOut () {
  return uni.flux.http.get('/external/reader/v1/readerLoginOut').then(() => {
    // 清除token
    // #ifdef MP-WEIXIN
    getMiniProgramLoginCode()
    logout()
    // #endif

    // #ifdef H5
    uni.flux.store.commit('setBookScene', 4)
    uni.flux.store.commit('setFreeTimes', 0)
    uni.flux.store.commit('setToken', '')
    uni.flux.store.commit('setUserInfoPhone', '')
    uni.flux.store.commit('setWxCode', '')
    // #endif
    return uni.flux.resolve()
  }).catch((err) => {
    return uni.flux.reject(new Error(err))
  })
}

/**
 * 600状态码 退出
 */
export function logout (type) {
  uni.flux.store.commit('setBookScene', 4)
  uni.flux.store.commit('setFreeTimes', 0)
  // uni.flux.store.commit('setToken', '')
  uni.flux.store.commit('setUserInfoPhone', '')
  // 再重新获取token

  // // #ifdef MP-WEIXIN
  // authorize()
  // // #endif
  //
  // // #ifdef H5
  // if (type !== 600) {
  //   h5LoginInit()
  // }
  // // #endif
}

export function getCode ({ phone }) {
  return uni.flux.http.get('/external/code/v1/getCode', { phone })
}

/**
 * 小程序和H5 购买课程时 修改手机号码
 * @param phone
 * @param code
 * @returns {*}
 */
export function checkCode ({ phone, code }) {
  return uni.flux.http.get('/external/code/v1/checkCode', { phone, code, source: 0 }).then(token => {
    return uni.flux.resolve()
  }).catch((err) => {
    return uni.flux.reject(new Error(err))
  })
}

/**
 * h5 login
 * @param phone
 * @param code
 * @returns {*}
 */
export function h5Login ({ phone, code }) {
  let api = '/external/code/v1/h5Login'
  if (uni.flux.store.state.env.isDev && uni.flux.store.state.env.isH5) {
    api = '/external/code/v1/devH5Login'
  }
  return uni.flux.http.get(api, { phone, code }).then(res => {
    uni.flux.store.commit('setIsRedirect', false)
    return uni.flux.resolve(res)
  }).catch(errorMsg => {
    uni.showToast({ icon: 'none', title: errorMsg || '登录失败，请检查手机号码和短信验正码是否正确' })
    return uni.flux.reject()
    // 重新获取token
    // return uni.flux.$api.user.h5Authorize(uni.flux.store.state.wxCode)
  })
}

/**
 * 登录成功后更新书籍信息
 * 场景 体验次数
 */

export function updateBookInfo () {
  if (uni.flux.store.state.bookId) {
    return uni.flux.$api.book.getBookInfo()
  }
}

/**
 * H5 重定向
 */
export function forWard (type) {
  // #ifdef H5
  if (!uni.flux.store.state.env.isDev && uni.flux.store.state.env.isH5) {
    uni.flux.store.commit('setWxCode', '')
    uni.removeStorageSync('wxCode')
    console.log('forWard', window.wxH5Authorize)
    if (type === 1) {
      window.wxH5Authorize.forWard()
    } else {
      window.wxH5Authorize.authorize()
    }
    // uni.flux.WxH5Authorize.authorize()
  }
  // #endif
}
